<template>
    <div style="font-weight:bold;text-align:center">工程文件浏览器</div>
    <el-tree 
    :data="graphTreeData" 
    :expand-on-click-node="false" 
    :default-expand-all="true"
    :props="defaultProps" @node-click="handleNodeClick" highlight-current />
</template>
  
<script  setup>
import { useStore } from 'vuex';
const store = useStore();
import { ref, onMounted } from 'vue'
import axios from 'axios';
import { FileAccessSvc } from '../../script/manage/service/FileAccessSvc';

onMounted(() => {
    console.log("FolderTree onMounted**********************");
    refreshData();
})

const handleNodeClick = (nodeData) => {
    let uuid = nodeData.id;
    console.log("uuid:" + uuid + "  name:" + nodeData.label);
    FileAccessSvc.open(uuid);
}

const graphTreeData = ref([])

const defaultProps = ref({
    children: 'children',
    label: 'label',
})


const parseToTreeData = (fileList) => {

    let treeDataList = [];
    fileList.forEach(p => {
        let t = { label: p.name, id: p.uuid, pid: p.parent, children: [] };
        treeDataList.push(t);
    });
    let rootNode = { label: 'root', id: 'root', pid: '', children: [] };

    treeDataList.forEach(parent => {
        if (parent.pid == "root") {
            rootNode.children.push(parent);
        }
        treeDataList.forEach(child => {
            if (child != parent && child.pid == parent.id) {
                parent.children.push(child);
            }
        });
    });

    let disRootNode = rootNode;
    if (rootNode.children.length == 1) {
        disRootNode = rootNode.children[0];
    }

    graphTreeData.value = [];
    graphTreeData.value.push(disRootNode);
}

const parseFiles = (fileJsonObjArray) => {
    console.log("parseFiles---------");
    let fileList = [];
    for (var i = 0; i < fileJsonObjArray.length; i++) {
        var unitObj = fileJsonObjArray[i];
        let uuid = unitObj["uuid"];
        let name = unitObj["name"];
        let parent = unitObj["parent"];
        let iconURL = unitObj["iconURL"];
        let newFile = { uuid, name, parent, iconURL };
        fileList.push(newFile);
    }
    parseToTreeData(fileList);
}
const getAllFiles = () => {
    var url = "api/graph/getProject";
    let curentProjID = window.gstore.state.curentFile["projectid"];
    if (curentProjID && curentProjID.length > 1) {
        let userid = store.state.uid;
        if (!userid || (userid && userid.length == 0)){
            userid = "longx13";
        }
        var postObj = { "pid": curentProjID ,userid};
        axios.post(url, postObj).then(res => {
            console.log(res.data);
            parseFiles(res.data);
        }).catch(function (error) {
            console.log(error);
        })
    }
    else{
        graphTreeData.value = [];
    }
}

const refreshData = () => {
    getAllFiles();
}

defineExpose({
    refreshData
});

</script>
  ../../script/manage/service/FileAccessSvc